<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace app\plugins\controller;

use think\Page;
use think\Db;
use weapp\Users\model\UsersModel;

class Users extends Base
{
	public $users = [
        'users_id' => 0,
        'admin_id' => 0,
        'nickname' => '游客',
    ];
	 public $code = 'users';
    /**
     * 构造方法
     */
    public function __construct(){
        parent::__construct();
		$users = Db::name('weapp')->where('code', 'Users')->find();
		if ($users['status'] < 0) {
            $this->error('请后台启用签到插件！');
        }
		
		/*加载到模板*/

        $this->assign('users', $this->users);
        $this->assign('nickname', $this->nickname);
        $this->assign('AdminParentId', $this->parent_id);
		
		$this->Code = 'users/';
		/*会员功能是否开启*/
        $logut_redirect_url = '';
        $msg = '';
        $this->usersConfig = getUsersConfigData('all');
        $web_users_switch = tpCache('web.web_users_switch');
        if (empty($web_users_switch) || isset($this->usersConfig['users_open_register']) && $this->usersConfig['users_open_register'] == 1) { 
            // 前台会员中心已关闭
            $logut_redirect_url = ROOT_DIR.'/';
            $msg = '会员中心尚未开启！';
        }
        if (!empty($logut_redirect_url)) {
            // 清理session并回到首页
            session('users_id', null);
            session('users', null);
            $this->error($msg, $logut_redirect_url);
            exit;
        }
		$Method = request()->action();
		$this->assign('Method',$Method);
        /* END */
    }

    /**
     * index
     */
    public function user()
    {
		
		$param = input('param.');

		if(empty($param['id']) && $param !== $param['id']){
			$this->error('页面打开失败');
		}
		$users = Db::name('users')
		    ->field('a.*,b.level_name')
		    ->alias('a')
			->join('__USERS_LEVEL__ b', 'b.level_id = a.level', 'LEFT')
		    ->where(['a.users_id'=>$param['id']])
			->find();
		if(empty($users)){
			$this->error('会员不存在');
		}
		$list = Db::name('users_parameter')
		    ->alias('a')
			->field('a.title,a.dtype,b.info')
			->join('__USERS_LIST__ b', 'b.para_id = a.para_id', 'LEFT')
			->where(['b.users_id'=>$param[id]])
			->select();

		$this->assign('list', $list);
        $this->assign('users', $users);

		$users_id = session('users_id');
		$cncount = Db::name('weapp_usersconcern')->where([
		    'cn_users_id'   => $param['id'],
			'status' =>  1,
            'lang'  => $this->home_lang,
		])->count();
		$count = Db::name('weapp_usersconcern')->where([
            'users_id'  => $param['id'],
			'status' =>  1,
            'lang'  => $this->home_lang,
        ])->count();
		$arccount = Db::name('archives')->where([
            'users_id'  => $param['id'],
			'status' =>  1,
			'arcrank' =>  0,
            'lang'  => $this->home_lang,
        ])->count();
		$this->assign('count', $count);
        $this->assign('cncount', $cncount);
		$this->assign('arccount', $arccount);
		//投稿
		$arclist = [];
		$map = (['users_id' => $param['id']]);
		$countt = Db::name('archives')->where($map)->count($param['id']);// 查询满足要求的总记录数
        $pageObj = new Page($countt, 20);// 实例化分页类 传入总记录数和每页显示的记录数
		$arclist['data'] = Db::name('archives')
		    ->alias('a')
			->field('a.*,b.*,c.dirname,c.dirpath')
			->join('__USERS__ b', 'b.users_id = a.users_id', 'LEFT')
			 ->join('__ARCTYPE__ c', 'a.typeid = c.id', 'LEFT')
		    ->where([
                'a.users_id'  => $param['id'],
			    'a.status' =>  1,
			    'a.arcrank' =>  0,
                'a.lang'  => $this->home_lang,
            ])->order('a.aid desc')->limit($pageObj->firstRow.','.$pageObj->listRows)->select();
		$seo_pseudo = tpCache('seo.seo_pseudo');
        foreach ($arclist['data'] as $key => $val) {
			$val['litpic'] = get_default_pic($val['litpic']);
            if ($seo_pseudo == 2) { // 生成静态模式下，以动态URL预览
                $arcurl  = arcurl('home/View/index', $val, true, true, 1, 1);
            } else {
                $arcurl  = arcurl('home/View/index', $val);
            }
			$arclist['data'][$key] = $val;
            $arclist['data'][$key]['arcurl']  = $arcurl;
			
        }
		$eyou = array(
            'field' => $arclist,
        );
        // 数据
        $this->assign('eyou', $eyou);
		$pageStr = $pageObj->show(); // 分页显示输出
		
		$this->assign('pageStr', $pageStr); // 赋值分页输出
        $this->assign('pageObj', $pageObj); // 赋值分页对象
		//投稿结束
		$tableName = 'ey_weapp_collection';
        $isTable = Db::query('SHOW TABLES LIKE'."'".$tableName."'");
		$this->assign('isTable', $isTable);
		$askName = 'ey_weapp_ask';
        $isask = Db::query('SHOW TABLES LIKE'."'".$askName."'");
		$this->assign('isask', $isask);
		$html = $this->fetch($this->code.'/'.THEME_STYLE.'/index');
        return $html;
		
    }
    //收藏
	public function usercol()
    {
		
		$param = input('param.');

		if(empty($param['id']) && $param !== $param['id']){
			$this->error('页面打开失败');
		}
		$users = Db::name('users')
		    ->field('a.*,b.level_name')
		    ->alias('a')
			->join('__USERS_LEVEL__ b', 'b.level_id = a.level', 'LEFT')
		    ->where(['a.users_id'=>$param['id']])
			->find();
		if(empty($users)){
			$this->error('会员不存在');
		}
		$list = Db::name('users_parameter')
		    ->alias('a')
			->field('a.title,a.dtype,b.info')
			->join('__USERS_LIST__ b', 'b.para_id = a.para_id', 'LEFT')
			->where(['b.users_id'=>$param[id]])
			->select();

		$this->assign('list', $list);
        $this->assign('users', $users);

		$users_id = session('users_id');
		$cncount = Db::name('weapp_usersconcern')->where([
		    'cn_users_id'   => $param['id'],
			'status' =>  1,
            'lang'  => $this->home_lang,
		])->count();
		$count = Db::name('weapp_usersconcern')->where([
            'users_id'  => $param['id'],
			'status' =>  1,
            'lang'  => $this->home_lang,
        ])->count();
		$arccount = Db::name('archives')->where([
            'users_id'  => $param['id'],
			'status' =>  1,
			'arcrank' =>  0,
            'lang'  => $this->home_lang,
        ])->count();
		$this->assign('count', $count);
        $this->assign('cncount', $cncount);
		$this->assign('arccount', $arccount);
		//收藏
		$arclist = [];
		$arcrpw = Db::name('weapp_collection')->where(['users_id' => $param['id']])->find();
		$map = (['title' => $arcrpw['title']]);
		$countt = Db::name('archives')->where($map)->count($param['id']);// 查询满足要求的总记录数
        $pageObj = new Page($countt, 20);// 实例化分页类 传入总记录数和每页显示的记录数
		$arclist['data'] = Db::name('weapp_collection')
		    ->alias('a')
			->field('a.*,d.dirpath,d.dirname,b.*,c.*')
			->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
			->join('__ARCHIVES__ c', 'c.title = a.title', 'LEFT')
			->join('__ARCTYPE__ d', 'c.typeid = d.id', 'LEFT')
		    ->where([
			    'a.users_id'  => $param['id'],
                'a.lang'  => $this->home_lang,
            ])->order('a.id desc')->limit($pageObj->firstRow.','.$pageObj->listRows)->select();
		$seo_pseudo = tpCache('seo.seo_pseudo');
		foreach ($arclist['data'] as $key => $val) {
			$val['litpic'] = get_default_pic($val['litpic']);
            if ($seo_pseudo == 2) { // 生成静态模式下，以动态URL预览
                $arcurl  = arcurl('home/View/index', $val, true, true, 1, 1);
            } else {
                $arcurl  = arcurl('home/View/index', $val);
            }
			$arclist['data'][$key] = $val;
            $arclist['data'][$key]['arcurl']  = $arcurl;
        }
		$eyou = array(
            'field' => $arclist,
        );
        // 数据
        $this->assign('eyou', $eyou);
		
		$pageStr = $pageObj->show(); // 分页显示输出
		
		$this->assign('pageStr', $pageStr); // 赋值分页输出
        $this->assign('pageObj', $pageObj); // 赋值分页对象
		//收藏结束
		$tableName = 'ey_weapp_collection';
        $isTable = Db::query('SHOW TABLES LIKE'."'".$tableName."'");
		$this->assign('isTable', $isTable);
		$askName = 'ey_weapp_ask';
        $isask = Db::query('SHOW TABLES LIKE'."'".$askName."'");
		$this->assign('isask', $isask);
		$html = $this->fetch($this->code.'/'.THEME_STYLE.'/index_usercol');
        return $html;
		
    }
	//下载
	public function userdow()
    {
		
		$param = input('param.');

		if(empty($param['id']) && $param !== $param['id']){
			$this->error('页面打开失败');
		}
		$users = Db::name('users')
		    ->field('a.*,b.level_name')
		    ->alias('a')
			->join('__USERS_LEVEL__ b', 'b.level_id = a.level', 'LEFT')
		    ->where(['a.users_id'=>$param['id']])
			->find();
		if(empty($users)){
			$this->error('会员不存在');
		}
		$list = Db::name('users_parameter')
		    ->alias('a')
			->field('a.title,a.dtype,b.info')
			->join('__USERS_LIST__ b', 'b.para_id = a.para_id', 'LEFT')
			->where(['b.users_id'=>$param[id]])
			->select();

		$this->assign('list', $list);
        $this->assign('users', $users);

		$users_id = session('users_id');
		$cncount = Db::name('weapp_usersconcern')->where([
		    'cn_users_id'   => $param['id'],
			'status' =>  1,
            'lang'  => $this->home_lang,
		])->count();
		$count = Db::name('weapp_usersconcern')->where([
            'users_id'  => $param['id'],
			'status' =>  1,
            'lang'  => $this->home_lang,
        ])->count();
		$arccount = Db::name('archives')->where([
            'users_id'  => $param['id'],
			'status' =>  1,
			'arcrank' =>  0,
            'lang'  => $this->home_lang,
        ])->count();
		$this->assign('count', $count);
        $this->assign('cncount', $cncount);
		$this->assign('arccount', $arccount);
		//下载
		$arclist = [];
		$map = (['users_id' => $param['id']]);
		$countt = Db::name('download_log')->where($map)->count($param['id']);// 查询满足要求的总记录数
        $pageObj = new Page($countt, 20);// 实例化分页类 传入总记录数和每页显示的记录数
		$arclist['data'] = Db::name('download_log')
		    ->alias('a')
			->field('a.*,e.dirpath,e.dirname,b.nickname,b.head_pic,d.litpic')
			->join('__USERS__ b', 'b.users_id = a.users_id', 'LEFT')
			->join('__DOWNLOAD_FILE__ c', 'a.file_id = c.file_id', 'LEFT')
			->join('__ARCHIVES__ d', 'a.aid = d.aid', 'LEFT')
			->join('__ARCTYPE__ e', 'd.typeid = e.id', 'LEFT')
		    ->where([
                'a.users_id'  => $param['id'],
            ])->order('a.log_id desc')->limit($pageObj->firstRow.','.$pageObj->listRows)->select();
			
		$seo_pseudo = tpCache('seo.seo_pseudo');
		foreach ($arclist['data'] as $key => $val) {
			$val['litpic'] = get_default_pic($val['litpic']);
            if ($seo_pseudo == 2) { // 生成静态模式下，以动态URL预览
                $arcurl  = arcurl('home/View/index', $val, true, true, 1, 1);
            } else {
                $arcurl  = arcurl('home/View/index', $val);
            }
			$arclist['data'][$key] = $val;
            $arclist['data'][$key]['arcurl']  = $arcurl;
        }
		$eyou = array(
            'field' => $arclist,
        );
        // 数据
        $this->assign('eyou', $eyou);
		
		$pageStr = $pageObj->show(); // 分页显示输出
		$this->assign('pageStr', $pageStr); // 赋值分页输出
        $this->assign('pageObj', $pageObj); // 赋值分页对象
		//下载结束
		$tableName = 'ey_weapp_collection';
        $isTable = Db::query('SHOW TABLES LIKE'."'".$tableName."'");
		$this->assign('isTable', $isTable);
		$askName = 'ey_weapp_ask';
        $isask = Db::query('SHOW TABLES LIKE'."'".$askName."'");
		$this->assign('isask', $isask);
		$html = $this->fetch($this->code.'/'.THEME_STYLE.'/index_userdow');
        return $html;
		
    }
	//问答
	public function userask()
    {
		
		$param = input('param.');

		if(empty($param['id']) && $param !== $param['id']){
			$this->error('页面打开失败');
		}
		$users = Db::name('users')
		    ->field('a.*,b.level_name')
		    ->alias('a')
			->join('__USERS_LEVEL__ b', 'b.level_id = a.level', 'LEFT')
		    ->where(['a.users_id'=>$param['id']])
			->find();
		if(empty($users)){
			$this->error('会员不存在');
		}
		$list = Db::name('users_parameter')
		    ->alias('a')
			->field('a.title,a.dtype,b.info')
			->join('__USERS_LIST__ b', 'b.para_id = a.para_id', 'LEFT')
			->where(['b.users_id'=>$param[id]])
			->select();

		$this->assign('list', $list);
        $this->assign('users', $users);

		$users_id = session('users_id');
		$cncount = Db::name('weapp_usersconcern')->where([
		    'cn_users_id'   => $param['id'],
			'status' =>  1,
            'lang'  => $this->home_lang,
		])->count();
		$count = Db::name('weapp_usersconcern')->where([
            'users_id'  => $param['id'],
			'status' =>  1,
            'lang'  => $this->home_lang,
        ])->count();
		$arccount = Db::name('archives')->where([
            'users_id'  => $param['id'],
			'status' =>  1,
			'arcrank' =>  0,
            'lang'  => $this->home_lang,
        ])->count();
		$this->assign('count', $count);
        $this->assign('cncount', $cncount);
		$this->assign('arccount', $arccount);
		//下载
		$asklist = [];
		$map = (['users_id' => $param['id']]);
		$countt = Db::name('weapp_ask')->where($map)->count($param['id']);// 查询满足要求的总记录数
        $pageObj = new Page($countt, 20);// 实例化分页类 传入总记录数和每页显示的记录数
		$asklist['AskData'] = Db::name('weapp_ask')
		    ->alias('a')
			->field('a.*,b.nickname,b.head_pic,c.type_id,c.type_name')
			->join('__USERS__ b', 'b.users_id = a.users_id', 'LEFT')
			->join('__WEAPP_ASK_TYPE__ c', 'c.type_id= a.type_id', 'LEFT')
		    ->where([
                'a.users_id'  => $param['id'],
            ])->order('a.ask_id desc')->limit($pageObj->firstRow.','.$pageObj->listRows)->select();
		foreach ($asklist['AskData'] as $key => $val) {
			$val['litpic'] = get_default_pic($val['litpic']);
            $AskUrl = ROOT_DIR.'/index.php?m=plugins&c=Ask&a=details&ask_id='.$val['ask_id'];
			if (isset($val['answer_id']) && !empty($val['answer_id'])) {
                $preg = '/<img.*?src=[\"|\']?(.*?)[\"|\']?\s.*?>/i';
                $val['content'] = htmlspecialchars_decode($value['content']);
                $val['content'] = preg_replace($preg,'[图片]',$value['content']);
                $val['content'] = strip_tags($value['content']);
                $asklist['AskData'][$key]['content'] = mb_strimwidth($value['content'], 0, 120, "...");
            }
			$asklist['AskData'][$key] = $val;
            $asklist['AskData'][$key]['AskUrl']  = $AskUrl;
        }
		$eyou = array(
            'field' => $asklist,
        );
        // 数据
        $this->assign('eyou', $eyou);
		
		$pageStr = $pageObj->show(); // 分页显示输出
		$this->assign('pageStr', $pageStr); // 赋值分页输出
        $this->assign('pageObj', $pageObj); // 赋值分页对象
		//问答结束
		$tableName = 'ey_weapp_collection';
        $isTable = Db::query('SHOW TABLES LIKE'."'".$tableName."'");
		$this->assign('isTable', $isTable);
		$askName = 'ey_weapp_ask';
        $isask = Db::query('SHOW TABLES LIKE'."'".$askName."'");
		$this->assign('isask', $isask);
		$html = $this->fetch($this->code.'/'.THEME_STYLE.'/index_userask');
        return $html;
		
    }
	//关注
	public function usercon()
    {
		
		$param = input('param.');

		if(empty($param['id']) && $param !== $param['id']){
			$this->error('页面打开失败');
		}
		$users = Db::name('users')
		    ->field('a.*,b.level_name')
		    ->alias('a')
			->join('__USERS_LEVEL__ b', 'b.level_id = a.level', 'LEFT')
		    ->where(['a.users_id'=>$param['id']])
			->find();
		if(empty($users)){
			$this->error('会员不存在');
		}
		$list = Db::name('users_parameter')
		    ->alias('a')
			->field('a.title,a.dtype,b.info')
			->join('__USERS_LIST__ b', 'b.para_id = a.para_id', 'LEFT')
			->where(['b.users_id'=>$param[id]])
			->select();

		$this->assign('list', $list);
        $this->assign('users', $users);

		$users_id = session('users_id');
		$cncount = Db::name('weapp_usersconcern')->where([
		    'cn_users_id'   => $param['id'],
			'status' =>  1,
            'lang'  => $this->home_lang,
		])->count();
		$count = Db::name('weapp_usersconcern')->where([
            'users_id'  => $param['id'],
			'status' =>  1,
            'lang'  => $this->home_lang,
        ])->count();
		$arccount = Db::name('archives')->where([
            'users_id'  => $param['id'],
			'status' =>  1,
			'arcrank' =>  0,
            'lang'  => $this->home_lang,
        ])->count();
		$this->assign('count', $count);
        $this->assign('cncount', $cncount);
		$this->assign('arccount', $arccount);
		//关注
		$arclist = [];
		$map = (['users_id' => $param['id']]);
		$countt = Db::name('weapp_usersconcern')->where($map)->count($param['id']);// 查询满足要求的总记录数
        $pageObj = new Page($countt, 20);// 实例化分页类 传入总记录数和每页显示的记录数
		$arclist['data'] = Db::name('weapp_usersconcern')
		    ->alias('a')
			->field('a.*,b.nickname,b.head_pic')
			->join('__USERS__ b', 'b.users_id = a.cn_users_id', 'LEFT')
		    ->where([
                'a.users_id'  => $param['id'],
            ])->order('a.id desc')->limit($pageObj->firstRow.','.$pageObj->listRows)->select();
		$seo_pseudo = tpCache('seo.seo_pseudo');
		foreach ($arclist['data'] as $key => $val) {
			$val['litpic'] = get_default_pic($val['litpic']);
			$arcurl = ROOT_DIR.'/index.php?m=plugins&c=Users&a=user&id='.$val['cn_users_id'];
            
			$arclist['data'][$key] = $val;
            $arclist['data'][$key]['arcurl']  = $arcurl;
			
        }
		$eyou = array(
            'field' => $arclist,
        );
        // 数据
        $this->assign('eyou', $eyou);
		
		$pageStr = $pageObj->show(); // 分页显示输出
		$this->assign('pageStr', $pageStr); // 赋值分页输出
        $this->assign('pageObj', $pageObj); // 赋值分页对象
		//关注结束
		$tableName = 'ey_weapp_collection';
        $isTable = Db::query('SHOW TABLES LIKE'."'".$tableName."'");
		$this->assign('isTable', $isTable);
		$askName = 'ey_weapp_ask';
        $isask = Db::query('SHOW TABLES LIKE'."'".$askName."'");
		$this->assign('isask', $isask);
		$html = $this->fetch($this->code.'/'.THEME_STYLE.'/index_usercon');
        return $html;
		
    }
	public function ajax_save()
	{
		if (IS_AJAX) {
			
			$cn_users_id = input('param.cn_users_id/s');
            $cn_users_id = urldecode($cn_users_id);
			$users_id = session('users_id');
			if (empty($users_id)) {
                $this->error('请先登录！');
            }
			if ($users_id == $cn_users_id) {
                $this->error('请不要给自己关注！');
            }
			$row = Db::name('weapp_usersconcern')->where([
                'users_id'  => $users_id,
				'cn_users_id'   => $cn_users_id,
				'status' =>  1,
                'lang'  => $this->home_lang,
            ])->find();
			if (empty($row)) {
				$r = Db::name('weapp_usersconcern')->add([
                    'users_id'  => $users_id,
                    'cn_users_id'   => $cn_users_id,
                    'lang'  => $this->home_lang,
					'status' =>  1,
                    'add_time'  => getTime(),
                    'update_time' => getTime(),
                ]);
				if (!empty($r)) {
                    $this->success('关注成功', $cn_users_id, ['opt'=>'add', 'afterHtml'=>'取消关注']);
                }
			}else {
				$r = Db::name('weapp_usersconcern')->where([
                    'users_id'  => $users_id,
                    'cn_users_id'   => $cn_users_id,
					'status' =>  1,
                    'lang'  => $this->home_lang,
                ])->delete();
                $this->success('取消成功', $cn_users_id, ['opt'=>'cancel', 'afterHtml'=>'关注']);
			}
			$this->error('关注失败', $cn_users_id, ['afterHtml'=>'关注']);
		}
		abort(404);
	}
	/**
     * 判断是否关注
     * @return [type] [description]
     */
    public function get_users()
    {
        \think\Session::pause(); // 暂停session，防止session阻塞机制

        if (IS_AJAX) {
            $cn_users_id = input('param.cn_users_id/s');
            $cn_users_id = urldecode($cn_users_id);

            $users_id = session('users_id');
            if (!empty($users_id)) {
                $count = Db::name('weapp_usersconcern')->where([
                    'users_id'  => $users_id,
                    'cn_users_id'   => $cn_users_id,
					'status' =>  1,
                    'lang'  => $this->home_lang,
                ])->count();
                if (!empty($count)) {
                    $this->success('已关注');
                }
            }
            $this->error('未关注');
        }
        abort(404);
    }
}